package com.yenlien.traceyun.plant.service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import com.yenlien.traceyun.plant.dao.ReapDetailDao;
import com.yenlien.traceyun.plant.entity.ReapDetail;

@Service
public class ReapDetailService {
    @Autowired
    private ReapDetailDao reapDetailDao;

    public Page<ReapDetail> findByList(final ReapDetail reapDetail) {
        Pageable pageable = PageRequest.of(reapDetail.getPage(), reapDetail.getPageSize(), Sort.Direction.DESC, ("createtime"));
        return reapDetailDao.findAll(new Specification<ReapDetail>() {
            private static final long serialVersionUID = -1396496630802017658L;

            @Override
            public Predicate toPredicate(Root<ReapDetail> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<String> reapName = root.get("reapName");
                Path<String> soilName = root.get("soilName");
                //构造查询条件
                List<Predicate> list = new ArrayList<Predicate>();
                if (!StringUtils.isEmpty(reapDetail.getReapName())) {
                    list.add(cb.equal(reapName, reapDetail.getReapName()));
                }
                if (!StringUtils.isEmpty(reapDetail.getSoilName())) {
                    list.add(cb.equal(soilName, reapDetail.getSoilName()));
                }
                Predicate[] predicateA = new Predicate[list.size()];
                return cb.and(list.toArray(predicateA));
            }
        }, pageable);
    }

    public List<String> findAllBreed() {
        return reapDetailDao.findAllBreed();
    }

    public ReapDetail findById(String id) {
        return reapDetailDao.findById(id);
    }
}
